package com.wfh.activity;

import com.wfh.R;
import com.wfh.util.MyDialog;
import com.wfh.util.Util;

import android.os.Bundle;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class RegistActivity extends CommonActivity {

	private EditText username, password;
	private Button regist;
	final String numberpattern = "^((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$";
	final String passwordpattern = "^(\\S+[a-z A-Z 0-9]){2,}$";
	private MyDialog dialog;
	private boolean mBound = true;
	private BroadcastReceiver datareceiver;
	private String user;
	private String pass;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState, R.layout.activity_regist);

		username = (EditText) findViewById(R.id.editText1);
		password = (EditText) findViewById(R.id.editText2);
		regist = (Button) findViewById(R.id.button1);
		dialog = MyDialog.create(this);

		// 注册recevier广播接收器
		IntentFilter filter = new IntentFilter();
		filter.addAction(Util.D_REGIST);
		datareceiver = new DataReceiver();
		registerReceiver(datareceiver, filter);

		regist.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				user = username.getText().toString();
				pass = password.getText().toString();
				if (!Util.isexist(numberpattern, user)) {
					Util.showToast(RegistActivity.this, "必须输入正确手机号码");
					return;
				}
				if (!Util.isexist(passwordpattern, pass)) {
					Util.showToast(RegistActivity.this, "请输入3位以上密码,不允许空格");
					return;
				}

				Bundle bd = new Bundle();
				bd.putString("user", user);
				bd.putString("pass", pass);
				if(mBound==false) return;
				HomeActivity.service.regist(RegistActivity.this,
						new Intent().putExtras(bd));
				mBound=false;
				dialog.show();

			}
		});

	}

	// 接收器
	private class DataReceiver extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			Bundle bd = intent.getExtras();
			dialog.hide();
			mBound=true;
			if(bd.getString("ret")==null){
				Util.showToast(RegistActivity.this, "出错了");
				return;
			}else if(bd.getString("ret").equals("1")){
				Util.showToast(RegistActivity.this, "注册成功,请登录");
				Util.startactivity(RegistActivity.this, LoginActivity.class);
				RegistActivity.this.finish();
				return;
			}else if(bd.getString("ret").equals("100")){
				Util.showToast(RegistActivity.this, "此用户已经注册");
				return;
			}
		}
	}

	@Override
	protected void onDestroy() {
		if (dialog != null)
			dialog.cancel();
		if(datareceiver!=null) unregisterReceiver(datareceiver);
		super.onDestroy();
	}

}
